package com.note.app.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.note.common.domain.Share;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * 分享Mapper
 */
@Mapper
public interface ShareMapper extends BaseMapper<Share> {

    /**
     * 根据令牌查询分享
     * 
     * @param token 分享令牌
     * @return 分享信息
     */
    @Select("SELECT * FROM share WHERE token = #{token} AND deleted = 0 AND expired_at > NOW() LIMIT 1")
    Share selectByToken(@Param("token") String token);
    
    /**
     * 分页查询用户分享的笔记
     * 
     * @param page 分页参数
     * @param userId 用户ID
     * @return 分页结果
     */
    @Select("SELECT * FROM share WHERE user_id = #{userId} AND deleted = 0 ORDER BY created_at DESC")
    IPage<Share> selectPageByUserId(Page<Share> page, @Param("userId") Long userId);
    
    /**
     * 根据笔记ID查询有效分享数量
     * 
     * @param noteId 笔记ID
     * @return 分享数量
     */
    @Select("SELECT COUNT(*) FROM share WHERE note_id = #{noteId} AND deleted = 0 AND expired_at > NOW()")
    int countActiveSharesByNoteId(@Param("noteId") Long noteId);
    
    /**
     * 根据笔记ID查询所有分享
     * 
     * @param page 分页参数
     * @param noteId 笔记ID
     * @return 分页结果
     */
    @Select("SELECT * FROM share WHERE note_id = #{noteId} AND deleted = 0 ORDER BY created_at DESC")
    IPage<Share> selectPageByNoteId(Page<Share> page, @Param("noteId") Long noteId);
    
    /**
     * 根据笔记ID获取最新的分享ID
     * 
     * @param noteId 笔记ID
     * @return 分享ID，如果没有则返回null
     */
    @Select("SELECT id FROM share WHERE note_id = #{noteId} AND deleted = 0 AND expired_at > NOW() ORDER BY created_at DESC LIMIT 1")
    Long getLatestShareIdByNoteId(@Param("noteId") Long noteId);
} 